package com.accesslimit.demo;

import com.google.common.util.concurrent.RateLimiter;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * 令牌桶算法 基于guava包
 *
 * @author sam
 */
public class TokenBucket {

    public static void main(String[] args) throws InterruptedException {
        // qps = 2
        RateLimiter rateLimiter = RateLimiter.create(1);
        for (int i = 0; i < 10; i++) {
            String time = LocalTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME);
            System.out.println(time + ": " + rateLimiter.tryAcquire());
//            System.out.println(time + ": " + rateLimiter.tryAcquire(1, 1, TimeUnit.SECONDS));
//            System.out.println(time + ": " + rateLimiter.tryAcquire(1, 500, TimeUnit.MILLISECONDS));
            Thread.sleep(250);
        }
    }

}
